package com.javabasic.net.netty;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author xiongmin
 * @Description Netty 3.X版本 Demo
 * @Date 2019/12/12 18:01
 * @Version 1.0
 **/
public class HelloServer {

    /**
     * @  查看源码
     * - 一断点
     * - 二打印
     * - 三看调用栈
     * - 四搜索
     * @param args
     */
    public static void main(String[] args) {
        // 服务类
        ServerBootstrap bootstrap = new ServerBootstrap();

        // boss 监听端口
        ExecutorService boss = Executors.newCachedThreadPool();
        // 为客户端服务，进行读写操作
        ExecutorService worker = Executors.newCachedThreadPool();

        // 设置niosocket工厂
        bootstrap.setFactory(new NioServerSocketChannelFactory(boss, worker));

        // 设置管道的工厂
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            @Override
            public ChannelPipeline getPipeline() throws Exception {
                ChannelPipeline pipeline = Channels.pipeline();
                pipeline.addLast("decode",new StringDecoder());
                pipeline.addLast("encode", new StringEncoder());
                pipeline.addLast("helloHandler", new HelloHandler());
                return pipeline;
            }
        });

        // 绑定端口
        bootstrap.bind(new InetSocketAddress(9000));

        System.out.println("服务端启动");
    }
}
